<template>
    <div class="jx-content" style="margin-top:0px">
        <div v-if="src =='' || show" >
           <div class="fr">
                 <button class="button-style saveBtn" @click="look" v-if="versionFile !=''" >预览</button>
           </div>
           <div class="fileUp">
                <div>
                     <div class="nofile-tip">
                         <img src="./../../../assets/images/courseware_tips.png" />
                     </div>
                     <button class="button-style uploadBtn">上传课件<input id="version-file-input" type="file" @change="getFile"></button>
                     <button class="button-style uploadBtn" v-if="roles == 'INTERNET_ADMIN'">多文件上传<input id="version-file-input-more" type="file" multiple="multiple" @change="getFileMore" ></button>
                     <p class="newadd"  v-if=" versionFile ==''">提示：仅支持PPTX格式文件上传</p>
                     <el-button class="button-style"  v-if=" versionFile !=''"  @click="downloadFile" :disabled='!flagDown'>下载课件</el-button>
                     <div v-if="versionFile!=''"  class="down-up">
                        <span style='margin-top:10px;' >{{versionFile}}</span>
                         <i class="iconfont icon-shanchu" @click="deleteFn"></i>
                        <span class="tips" >提示：仅支持PPTX格式文件上传</span>
                    </div>
                </div>
           </div>
        </div>
        <div v-if=" src !='' && !show ">
           <div class="fr">
                 <button class="button-style saveBtn" @click="repeatFn"  v-if=" src !='' ">修改</button>
           </div>
           <div class="iframse">
                <iframe width="101%"  :height="hei"  style='pverflow:hidden' allowfullscreen="true"  scrolling="no" allowtransparency="true" class="coursewareBox"  :src="'../../../../static/generic/web/viewer.html?file=/tes/course/'+courseId+/chapter/+chapterId+'/resource/read'"  frameborder="0"></iframe>
           </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                //文件名字
                versionFile:'',
                //假定的宽度和高度
                wid:0,
                hei:0,
                //是否展示
                show:'',
                //课程id
                courseId:'',
                //章节id
                chapterId:'',
                //url地址
                src:'',
                //是否允许下载
                flagDown:'',
                //下载文件
                down:'',
                //后台下载标识
                remark:'',
                //存储token值下载
                token:'',
                //角色
                roles:'',
            }
        },
        created() {
            // 从状态管理获取roles
            this.roles = this.$store.state.user.roles[0];
            let screenHeight=document.documentElement.clientHeight;
            this.chapterId = this.$localstorage.getLocalStorage('chapterInfoData').chapterId
            this.courseId = this.$localstorage.getLocalStorage('setCourseId')
            this.hei = screenHeight-300;
            this.init()
        },
        methods:{
            init(){
                let self = this
                self.$http.get('/tes/course/'+ self.courseId+'/chapter/'+self.chapterId+'/make/resource?types=2').then(response => {
                    let res = response.data
                    if(res.code == '200'){
                         if(res.data.courseware.displayVersion.length>0){
                                self.flagDown= res.data.courseware.displayVersion[0].download
                                self.src = res.data.courseware.displayVersion[0].filePath
                                self.versionFile =res.data.courseware.creativeVersion[0].fileName
                                self.down = res.data.courseware.creativeVersion[0].filePath
                                self.remark = res.data.courseware.creativeVersion[0].remark
                            }
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            //下载文件
             downloadFile(){
                let self = this
                self.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource/file-download/permission',{
                    remark :self.remark,
                    fileName : self.versionFile
                    }) .then((response) => {
                    let res = response.data
                if(res.code == '200'){
                    self.token=res.data
                    let downloadElement = document.createElement('a');
                    downloadElement.style.display = 'none';
                    downloadElement.href = '/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource/file-download?token='+self.token
                    downloadElement.download = self.versionVideo; //下载后文件名
                    downloadElement.click(); //点击下载
                    //document.body.removeChild(downloadElement); //下载完成移除元素
                    }else{
                        self.$message.error(res.message)
                    }
                })
                     //方式被pass是因为下载速度太慢
                    // self.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource/file-download',{  //此处的 courseId 是假定写死的值
                    //     remark :self.remark,
                    //     fileName : self.versionFile
                    // },{responseType: 'blob'}) .then((response) => {
                    //     let contentType = response.headers["content-type"]
                    //     if(contentType=='application/json;charset=UTF-8'){
                    //         self.$message.error(decodeURIComponent(response.headers["code-message"]))
                    //     } else {
                    //         let blob = new Blob([response.data], {type: response.headers['content-disposition']});
                    //         let fileName = self.versionFile
                    //         let url = window.URL.createObjectURL(blob);
                    //         let downloadElement = document.createElement('a');
                    //         downloadElement.style.display = 'none';
                    //         downloadElement.href = url;
                    //         downloadElement.download = fileName; //下载后文件名
                    //         document.body.appendChild(downloadElement);
                    //         downloadElement.click(); //点击下载
                    //         document.body.removeChild(downloadElement); //下载完成移除元素
                    //         window.URL.revokeObjectURL(url);
                    //     }
                    // }).catch(err => {
                    //     console.log(err)
                    // })

            },
            //修改
            repeatFn(){
               // console.log(11211)
                this.show=true
                this.src=''
            },
            //预览
            look(){
               // console.log(7777)
                this.show=false
                this.init()
            },
            //多文件上传
            getFileMore($event){
                let self =this
                let fileType = $event.target.files
                let nameFile1=$event.target.files[0].name
                let nameFile2=$event.target.files[1].name
                let fileType1 = nameFile1.substring((nameFile1.lastIndexOf('.') + 1), nameFile1.length) //取得后缀名
                let fileType2 = nameFile2.substring((nameFile2.lastIndexOf('.') + 1), nameFile2.length) //取得后缀名
                if( fileType1.toLowerCase() != "pptx" && fileType1.toLowerCase() != "pdf" || fileType2.toLowerCase() != "pptx" && fileType2.toLowerCase() != "pdf"  ){
                    this.$message.error('请上传pptx文件或者pdf文件')
                    return
                }
                 const loading = this.$loading({
                    lock: true,
                    text: '文件上传中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                 })
                let formData = new FormData();
                let files = $("#version-file-input-more");
                for (var i = 0; i < files[0].files.length; i++) {
                    formData.append("files", files[0].files[i]);
                    //console.log(files[0].files[i],78)
                }
                 this.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource-file?name=学习课件&resourceType=2', formData, {headers: {'Content-Type': 'multipart/form-data'}}).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        this.$message({
                            message: '上传成功',
                            type: 'success'
                        })
                        loading.close()
                      // this.versionFile = $event.target.files[0].name
                        $event.target.value=''
                        self.init()
                    }else if(res.code == '500'){
                        self.$message.error('上传失败，请检查文件中是否包含公式。若包含，请将公式转换为图片再上传')
                        loading.close()
                    }else{
                        loading.close()
                        $event.target.value=''
                        self.$message.error(res.message)
                    }
                 })
            },
            //文件上传
            getFile($event){
                let self =this
                 self.src=''
                let fileType = $event.target.files[0].name
                fileType = fileType.substring((fileType.lastIndexOf('.') + 1), fileType.length) //取得后缀名
                if( fileType.toLowerCase() != "pptx"){
                    this.$message.error('请上传pptx文件')
                    return
                }
                 const loading = this.$loading({
                    lock: true,
                    text: '文件上传中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                 })
                 let arr = [];
                 let formData = new FormData();

                 formData.append('files', $event.target.files[0]);

                 this.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource-file?name=学习课件&resourceType=2', formData, {headers: {'Content-Type': 'multipart/form-data'}}).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        this.$message({
                            message: '上传成功',
                            type: 'success'
                        })
                        loading.close()
                      // this.versionFile = $event.target.files[0].name
                        $event.target.value=''
                        self.init()
                        self.show=false
                        //window.location.reload(); 刷新好使
                    }else if(res.code == '500'){
                         self.$message.error('上传失败，请检查文件中是否包含公式。若包含，请将公式转换为图片再上传')
                         loading.close()
                    }else{
                        loading.close()
                        $event.target.value=''
                        self.$message.error(res.message)
                    }
                 })
            },
             //删除
            deleteFn(){
                let self = this;
                self.$confirm('是否确定删除?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                self.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource?resourceType=2',{
                    name:'学习课件'
                }).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        self.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        self.init()
                        self.versionFile =''
                        // window.location.reload(); 刷新好使
                    }else{
                        self.$message.error(res.message)
                    }
                 }).catch(err => {
                     console.log(err)
                })
             })
            },
        }
    }
</script>
<style scoped>
    body {
        overflow-x : hidden;
    }

</style>
<style scoped lang="scss">
 @import "./../../../styles/layout/color_variables";
 .jx-content{
     margin-top: 0px ;
     .nofile-tip{
         margin-bottom: 50px;
     }
     .fileUp{
         text-align: center;
         padding: 100px 0 300px;
          #version-file-input{
            position: absolute;
            left: 0;
            opacity: 0;
            height: 30px;
            top: 0px;
            width: 90px;
            cursor: pointer;
        }
          #version-file-input-more{
            position: absolute;
            left: 0;
            opacity: 0;
            height: 30px;
            top: 0px;
            width: 90px;
            cursor: pointer;

        }
        .down-up{
            margin:10px 0;
            .tips{
              margin-top:10px;
              color: $btn-blue
            }
        }
       .uploadBtn{
            margin-right: 30px;
            position: relative;

        }
        .icon-shanchu{
            color: $blue;
            font-size: 20px;
            vertical-align: sub;
            cursor: pointer;
            margin-right: 5px;
        }
     }
     .iframse{
         padding-top: 30px;
         clear: both;
     }
     .saveBtn{
         margin-top: 30px;
     }
     .newadd{
         padding: 15px 0;
         color:#1277eb;
     }
 }
</style>
